from PyQt4.QtGui import QWidget,QListWidgetItem,QFileDialog,QVBoxLayout
from PyQt4 import QtCore
from KUI.KStrategyUI.ui_KBatchTestWidget import Ui_KBatchTestWidget
from KReport.KStockListBrowseWidget import KStockListBrowseWidget
from KReport import KStocksItemModel, KStocksTableView
from KModel.KSingleStock import KSingleStock
from KTrade.KStockFeed import KStockFeed
import collections
class KBatchTestWidget(QWidget):
	


	''' The UI of strategy batch test '''
	def __init__(self, parent=None):
		super(KBatchTestWidget, self).__init__(parent)
		self.ui =  Ui_KBatchTestWidget()    
		self.ui.setupUi(self) 
		self.mutlithread=True # execut in seperate thread or not

		# add Report Window
		reportlayout=QVBoxLayout(self.ui.reportFrame)
		m_rpwgt=KStockListBrowseWidget(self,KStocksItemModel.KStocksItemModel())
		reportlayout.addWidget(m_rpwgt)
		m_rpwgt.ReportSelctionChanged.connect(self.parent().OnReportSelectionChanged) # notify central widget the selection change
		self.browsewgt=m_rpwgt
		# set up signal
		self.ui.BtnScan.clicked.connect(self.OnScan)
		self.ui.BtnCancel.clicked.connect(self.OnCancel)

	
	def OnStratgeySymbolFinished(self,	symbolname,resultdict):
		self.browsewgt.UpdateDynamicColumns(symbolname,resultdict)
		
	def OnCancel(self):
		if hasattr(self,'worker'):
			self.worker.Stop()

		
	def OnScan(self):
		# triggered when click scan
		self.worker=KBatchWorker()		
		self.worker.StratgeySymbolFinished.connect(self.OnStratgeySymbolFinished)		
		self.worker.SetStrategyWgt(self)
		
		self.mutlithread=True
		if self.mutlithread==True:
			self.worker.runScan()
		else:
			self.worker.ScanWithStrategy()
		
	
			
class KBatchWorker(QtCore.QObject):
	# work to execute scan in seperate thread
		finished=QtCore.pyqtSignal()
		StratgeySymbolFinished=QtCore.pyqtSignal(str, dict) # signal to notify GUI thread new results ready	
		
		def __init__(self, parent=None):
			QtCore.QObject.__init__(self,parent)
			self.batchwgt=None
		
		def SetStrategyWgt(self,wgt):
			# set the work method to execute
			self.batchwgt=wgt
		
		## apply scan in new thread
		def runScan(self):
	
			self.workthread = QtCore.QThread() ## execut in seperate thread
			self.Stopped=False
			self.moveToThread(self.workthread)
			self.workthread.finished.connect(self.workthread.deleteLater)
			self.workthread.started.connect(self.ScanWithStrategy)
	
			self.finished.connect(self.workthread.quit)
			self.finished.connect(self.deleteLater)    
			self.workthread.start()		
	
		def Stop(self):
			self.Stopped=True
			
		def ScanWithStrategy(self):
			# scan the list with selected strategy
			
			symbols=self.batchwgt.browsewgt.GetCurrentSymbolList()		
			straclass=self.batchwgt.ui.strategyTree.GetSelectedStrategyClass()
			m_stock=KSingleStock() # create its stock object		
			for each_symbol in symbols:
				(symbol,market,country)=each_symbol.split('.',3)
				m_stock.SetTick(country,market,symbol)	
				m_feed=KStockFeed(m_stock)
				m_stratgy=straclass(None,m_feed)
				m_stratgy.run()
				metricresult=m_stratgy.GetAllMetrics()
				# fill result into the table
				coldict=collections.OrderedDict(metricresult)		
				self.StratgeySymbolFinished.emit(each_symbol,coldict) #notify GUI	
				if self.Stopped==True:
					return # return if stopped by user
				

